<script>
export default {
  name: 'ChangeRoleDialog'
}
</script>
<script setup>
import $API from '@/api/index'
import { UsersModel } from '@/model/Users.js'
import { ref, getCurrentInstance, onUnmounted } from 'vue'

// console.log(getCurrentInstance())

onUnmounted(() => {
  form.vm.data.checkedRole = []
  handleCheckedRoleAllChange(form.vm.data.checkedRole)
})

const $emits = defineEmits(['confirm', 'close'])

const form = new UsersModel()

const { row } = defineProps(['row'])

form.setData({
  id: row.id,
  username: row.username
})

// 多选框
// 全选判定
const checkAll = ref(false)
// 半选判定
const isIndeterminate = ref(true)
// 选中角色
// const checkedRole = ref([])
// 全部角色
const roleAll = ref([])

// 更改全选方法
const handleCheckAllChange = val => {
  form.vm.data.checkedRole = val ? roleAll.value : []
  isIndeterminate.value = false
}
// 单选点击方法
const handleCheckedRoleAllChange = value => {
  const checkedCount = value.length
  checkAll.value = checkedCount === roleAll.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < roleAll.value.length
}

// 分配角色职位初始化
const roleCheckboxLoad = async function () {
  try {
    // 发请求
    const result = await $API.acl.user.reqToAssign(row.id)
    if (result?.data?.code === 200) {
      form.vm.data.checkedRole = result.data.data.assignRoles
      roleAll.value = result.data.data.allRolesList
      handleCheckedRoleAllChange(form.vm.data.checkedRole)
    }
  } catch (error) {}
}
roleCheckboxLoad()

// 保存分配角色编辑抽屉
const save = async function () {
  await form.doAssignRole()
  if (form.vm.status === 2) $emits('confirm')
}
</script>

<template>
  <el-form label-width="80px">
    <el-form-item
      label="用户姓名"
      prop="name"
    >
      <el-input
        v-model="form.vm.data.username"
        placeholder="请填写用户姓名"
        :disabled="true"
      />
    </el-form-item>
    <el-form-item
      label="角色列表"
      prop="name"
    >
      <el-checkbox
        v-model="checkAll"
        :indeterminate="isIndeterminate"
        @change="handleCheckAllChange"
      >
        全选
      </el-checkbox>
    </el-form-item>
    <el-form-item>
      <el-checkbox-group
        v-model="form.vm.data.checkedRole"
        @change="handleCheckedRoleAllChange"
      >
        <el-checkbox
          v-for="item in roleAll"
          :key="item.id"
          :label="item.roleName"
          :value="item"
        >
          {{ item.roleName }}
        </el-checkbox>
      </el-checkbox-group>
    </el-form-item>
  </el-form>

  <div>
    <el-button @click="$emits('close')">取消</el-button>
    <el-button
      type="primary"
      @click="save()"
    >
      确定
    </el-button>
  </div>
  <!-- <template #footer>
    <el-button @click="closeSetRoleEditor()">取消</el-button>
    <el-button type="primary" @click="save()"> 确定 </el-button>
  </template> -->
</template>

<style scoped lang="scss">
// start
</style>
